package org.aplombh.java.interview.leetcode;

import java.util.Arrays;

public class _994_腐烂的橘子 {
    public static void main(String[] args) {
        System.out.println(new _994_腐烂的橘子().orangesRotting(new int[][]{{0,1}}));
    }


    public static int[] dx = {0, 0, -1, +1};
    public static int[] dy = {-1, +1, 0, 0};

    public int orangesRotting(int[][] grid) {
        int[][] rot = new int[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++) {
            Arrays.fill(rot[i], -1);
        }
        int res = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 2) {
                    rot[i][j] = 0;
                    rotting(rot, grid, i, j, 0);
                }
            }
        }
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1 && rot[i][j] == -1)
                    return -1;
                res = Math.max(res, rot[i][j]);
            }
        }
        return res;
    }

    private void rotting(int[][] rot, int[][] grid, int i, int j, int deep) {
        for (int k = 0; k < 4; k++) {
            int x = dx[k] + i;
            int y = dy[k] + j;
            if (x > -1 && y > -1 && x < grid.length && y < grid[0].length && grid[x][y] != 0) {
                if (rot[x][y] == -1) {
                    rot[x][y] = deep + 1;
                } else if (rot[x][y] == 0 || rot[x][y] < deep + 1) {
                    continue;
                } else {
                    rot[x][y] = Math.min(rot[x][y], deep + 1);
                }
                rotting(rot, grid, x, y, deep + 1);
            }
        }
    }
}
